package com.sskj.motherboard.handler.strategy;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sskj.common.constant.RabbitMQConstant;
import com.sskj.common.dto.DeviceQueueMessage;
import com.sskj.common.dto.motherboard.OfflineMessage;
import com.sskj.common.enums.DeviceMessageTypeEnum;
import com.sskj.motherboard.constant.ChannelAttributesConstant;
import com.sskj.motherboard.server.ClientManager;
import com.sskj.motherboard.vo.FrameMessage;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Component
@Slf4j
public class OfflineMessageHandler implements IFrameMessageHandlerStrategy{

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void handle(ChannelHandlerContext channelHandlerContext, FrameMessage frameMessage) {
        String deviceId = channelHandlerContext.channel().attr(ChannelAttributesConstant.DEVICE_ID).get();
        if (deviceId != null) {
            ClientManager.unregisterClient(deviceId);       // 移除会话
            channelHandlerContext.channel().attr(ChannelAttributesConstant.DEVICE_ID).set(null);


            OfflineMessage offlineMessage = new OfflineMessage();
            offlineMessage.setDeviceId(deviceId);
            offlineMessage.setTime(LocalDateTime.now());
            try {
                String payload = objectMapper.writeValueAsString(offlineMessage);

                DeviceQueueMessage deviceQueueMessage = new DeviceQueueMessage();
                deviceQueueMessage.setType(DeviceMessageTypeEnum.OFFLINE.getType());
                deviceQueueMessage.setPayload(payload);
                amqpTemplate.convertAndSend(RabbitMQConstant.IOT_EXCHANGE, RabbitMQConstant.IOT_ROUTEING_KEY, objectMapper.writeValueAsString(deviceQueueMessage));
            } catch (JsonProcessingException e) {
                log.error("序列化异常。异常信息:{}", e.getMessage());
            }
        }
    }
}
